﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.Security;

using SSO;
using UMC;
using LMD.Lib.Interface;
/// <summary>
/// Summary description for ICPGeneralPage
/// </summary>
public abstract class ICPGeneralPage: Page
{
    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1111
     * Data ini nantinya diambil dari hasil login SSO
     */
    public String m_sxUID = String.Empty;
    public String m_sxUserName = String.Empty;
    public String sxUserInfo = String.Empty;
    public bool m_isAdmin = false;

    public List<ICPUserRole> m_lsPermittedRoles = new List<ICPUserRole>();
	public List<String> m_lsPrivilledges = new List<String>();

    public String PageName {
        get {
            return Path.GetFileName(Page.Request.PhysicalPath);
        }
    }

    public ICPGeneralPage()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    protected virtual void Logout()
    {
    }

    protected virtual void Page_Load(object sender, EventArgs e)
    {
        /* ==========================================================
         * ON POSTBACK
         * --> CHECK IF USER DOING A SEARCH
         * --> NO AUTHENTICATION NEEDED
         * ==========================================================
         */
        if (IsPostBack)
        {
            String sxSearchQuery = (Master as IMasterPage).ReadSearchQuery();

            if (!String.IsNullOrEmpty(sxSearchQuery))
            {
                (Master as IMasterPage).SetSearchMode(true);
                DoSearch(sxSearchQuery);
            }
        }

        /* ==========================================================
         * CEK AUTHENTICATION : _STARTS
         * ==========================================================
         */
        if (!String.IsNullOrEmpty(Request.QueryString["action"]))
        {
            if (Request.QueryString["action"].ToUpper() == "LOGOUT")
            {
                FormsAuthentication.SignOut();
                Response.Write("YOU HAVE BEEN LOGGED OUT");
                //Response.Write("<div onload=\"window.close();\"/>");
                //Response.Redirect("HTMLPage.htm", true);
                Response.End();
            }
        }

        /* ==========================================================
         * IF HAS BEEN AUTHENTICATED ~> JUST RETURN TO THE PAGE
         * ==========================================================
         */
        if (User.Identity.IsAuthenticated)
        {
            m_sxUID = ICPUser.ID;
            m_sxUserName = ICPUser.Name;
            m_isAdmin = ICPUser.IsAdmin;

            if (m_lsPermittedRoles.Count > 0)
            {
                if (!m_lsPermittedRoles.Contains(ICPUser.UserRole))
                {
                    Response.Write("YOU DON'T HAVE PRIVILEDGE TO VIEW THIS PAGE");
                    Response.End();
                }
            }
			//ambil privilledges ke UMC
            //UMC.Service UMCSvc = new UMC.Service();
            //String sxPriviledges = UMCSvc.GetFeaturesText("ICP", m_sxUID);

            // TODO: THISis by pass by ilham 10-10-2013
            UMC.Service UMCSvc = new UMC.Service();
            String sxPriviledges = "Relationship|News Feed|Company Profile";
            // end here

            String[] sxSplitted = sxPriviledges.Split(new String[] { "|" }, StringSplitOptions.None);
            foreach (String sxPriviledge in sxSplitted)
            {
                m_lsPrivilledges.Add(sxPriviledge);
            }
            return;
        }

        /* ==========================================================
         * IF RUN ON LOCALHOST ~> FAKE AUTHENTICATION, RETURN TO THE PAGE
         * ==========================================================
         */
        if (Request.Url.OriginalString.ToLower().Contains("project."))
        {
            HttpContext.Current.SkipAuthorization = true;
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|78040882|IHY|ARIE FIRMANSYAH|2", false);
            
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|83081010|BAR|BAYU ARDI RAHMANTO|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|71960578|BAR|TES DOANK|0", false);
            
            //FormsAuthentication.RedirectFromLoginPage("OK|68910186|KLH|KARLOS LAMHOT|0", false);
            FormsAuthentication.RedirectFromLoginPage("OK|83081010|BAR|BAYU ARDI RAHMANTO|0", false);
            return;
        }


        /* ==========================================================
         * IF RUN ON LOCALHOST ~> FAKE AUTHENTICATION, RETURN TO THE PAGE
         * ==========================================================
         */
        if (Request.Url.OriginalString.ToLower().Contains("localhost"))
        {
            HttpContext.Current.SkipAuthorization = true;
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|78040882|IHY|ARIE FIRMANSYAH|2", false);
            
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|83081010|BAR|BAYU ARDI RAHMANTO|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|71960578|BAR|TES DOANK|0", false);
            
            //FormsAuthentication.RedirectFromLoginPage("OK|68910186|KLH|KARLOS LAMHOT|0", false);
            FormsAuthentication.RedirectFromLoginPage("OK|83081010|BAR|BAYU ARDI RAHMANTO|0", false);
            return;
        }
		
        /* ==========================================================
         * addition: ilham 10-10-2013 
         * IF RUN ON CLOUD ~> FAKE AUTHENTICATION, RETURN TO THE PAGE
         * ==========================================================
         */
        if (Request.Url.OriginalString.ToLower().Contains("lintasmediadanawa"))
        {
            HttpContext.Current.SkipAuthorization = true;
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|78040882|IHY|ARIE FIRMANSYAH|2", false);
            
            //FormsAuthentication.RedirectFromLoginPage("OK|71910220|IHY|ROHIMAN|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|83081010|BAR|BAYU ARDI RAHMANTO|ADMIN", false);
            //FormsAuthentication.RedirectFromLoginPage("OK|71960578|BAR|TES DOANK|0", false);
            
            FormsAuthentication.RedirectFromLoginPage("OK|68910186|KLH|KARLOS LAMHOT|0", false);
            return;
        }




        /* ==========================================================
         * IF HAS NOT BEEN AUTHENTICATED
         * 1: DONT HAVE LASSOTICKET, REDIRECT TO PORTAL SSO
         * 2: ALREADY HAVE LASSOTICKET, VALIDATE THE TICKET USING WS
         * ==========================================================
         */
        if (String.IsNullOrEmpty(Request.QueryString["LassoTicketId"]))
        {
            String redUrl = ConfigurationManager.AppSettings["PortalSSO.Signin"] + "?SenderUrl=" + Request.Url.AbsoluteUri;
            Response.Redirect(redUrl);
        }
        else
        {
            // jika sudah mempunyai LassoTicketId, validate menggunakan WebService
            ValidateTicket UserValidator = new ValidateTicket();
            sxUserInfo = UserValidator.Validate("", Request.QueryString["LassoTicketId"]);

            if (!sxUserInfo.StartsWith("OK"))
            {
                Response.Write("SSO LOGIN ERROR!");
                Response.End();
            }

            // jika authenticated user, check apakah dia admin ICP atau bukan

            String sxTmpNIK = sxUserInfo.Split('|')[1];

            Cached.ICPAdminTable ccAdmin = new Cached.ICPAdminTable();
            DataView dv = new DataView(ccAdmin.GetAdminList(),
                String.Format("ADMIN_NO = '{0}'", sxTmpNIK), String.Empty, DataViewRowState.CurrentRows);

            if (dv.Count > 0)
            {
                m_isAdmin = true;
                sxUserInfo += "|" + ((int)ICPUserRole.Administrator).ToString();
            }
            else
            { 
                // jika bukan admin, cek apakah user punya hak akses ICP, dan ambil rolenya
                UMC.Service UMCSvc = new UMC.Service();
                String sxRole = UMCSvc.GetRolesText("ICP", sxTmpNIK);

                if (String.IsNullOrEmpty(sxRole))
                {
                    Response.Write("YOU HAVE NO ACCESS TO ICP!!!");
                    FormsAuthentication.SignOut();
                    Response.End();
                }
                else
                {
                    Cached.ICPUserRoleTable ccRole = new Cached.ICPUserRoleTable();

                    DataView dvRole = new DataView(ccRole.GetUserRoleList(),
                        String.Format("UMC_CODE = '{0}'", sxRole), String.Empty, DataViewRowState.CurrentRows);

                    if (dvRole.Count > 0)
                    {
                        sxUserInfo += "|" + dvRole[0]["ID"];
                    }
                    else
                    {
                        Response.Write("YOU HAVE A NEW ROLE THAT HASN'T BEEN REGISTERED IN ICP, PLEASE CONTACT YOUR ADMINISTRATOR");
                        FormsAuthentication.SignOut();
                        Response.End();
                    }
                }
            }

            FormsAuthentication.RedirectFromLoginPage(sxUserInfo, false);
            Response.Redirect(FormsAuthentication.DefaultUrl, true);
        }
    }

    protected virtual String GenerateSideMenu()
    {
        return GenerateSideMenu(String.Empty);
    }
    protected virtual String GenerateSideMenu(String sxPageParameter, params String[] sxParameters)
    {
        return MenuManager.GenerateMenu(m_lsPrivilledges, PageName + sxPageParameter, sxParameters);
    }
    public  virtual String GenerateUserProfileBox()
    {
        DateTime dtmLastLogin = DateTime.Now; //!!!!!!!!!!!!!!!!!!!!!!!!!! DUMMY
        return MenuManager.GenerateUserInfoBox(m_sxUID, m_sxUserName, dtmLastLogin);
    }

    protected abstract void DoSearch(String sxSearchQuery);
}
